package com.id.supaclean.common

/**
 * Created by YiGo on 2022/6/14.
 */
import android.net.Uri
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.IdRes
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions

/**
 * Created by DomenCai on 2020/4/24.
 */
open class BaseVHolder<T : BaseItemData>(parentGroup: ViewGroup, layoutId: Int) :
    RecyclerView.ViewHolder(
        LayoutInflater.from(parentGroup.context).inflate(layoutId, parentGroup, false)
    ) {

    private val viewSparseArray: SparseArray<View> by lazy { SparseArray<View>() }

    open fun updateView(data: T?, position: Int) = Unit

    @Suppress("UNCHECKED_CAST")
    protected fun <V : View?> findView(@IdRes id: Int): V? {
        var v: View? = viewSparseArray.get(id)
        if (v == null) {
            v = itemView.findViewById(id)
            viewSparseArray.put(id, v)
        }
        return v as V?
    }

    fun setVisible(id: Int, isVisible: Boolean) {
        findView<View>(id)?.isVisible = isVisible
    }

    fun setText(@IdRes id: Int, text: String?) {
        findView<TextView>(id)?.text = text
    }

    fun setImage(id: Int, uri: Uri?) {
        findView<ImageView>(id)?.apply {
            Glide.with(context)
                .asBitmap()
                .load(uri)
                .apply(RequestOptions().override(width, height).centerCrop())
                .into(this)
        }
    }
}